package com.joysuch.wwyt.edu.schedule;

import com.joysuch.wwyt.edu.entity.WwytEduCertificateUser;
import com.joysuch.wwyt.edu.enums.CertStatus;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author xsx
 * @version 1.0
 * @date 2022/9/6 15:21
 */
@Component
@Slf4j
public class EduCertificateSchedule {
    @Autowired
    private WwytEduCertificateUserService wwytEduCertificateUserService;

    /**
     * 查找过期的用户证书
     */
    @Scheduled(cron = "0 1 0 * * ?")
    public void task(){
        log.info("查找过期的用户证书定时任务开始执行");
        List<WwytEduCertificateUser> list = wwytEduCertificateUserService.findCertificates(new Date(), CertStatus.EXPIRING_SOON.status.toString());
        if (CollectionUtils.isNotEmpty(list)) {
            for (WwytEduCertificateUser wwytEduCertificateUser : list) {
                wwytEduCertificateUser.setCertStatus(CertStatus.EXPIRED.status.toString());
            }
        }

        // 待生效证书
        List<WwytEduCertificateUser> futureCertificates = wwytEduCertificateUserService.findFutureCertificates(new Date(), CertStatus.NO_EFFECTIVE.status.toString());
        if (CollectionUtils.isNotEmpty(futureCertificates)) {
            for (WwytEduCertificateUser wwytEduCertificateUser : futureCertificates) {
                wwytEduCertificateUser.setCertStatus(CertStatus.EFFECTIVE.status.toString());
            }
        }
        // 整合数据，批量更新
        list.addAll(futureCertificates);
        if (CollectionUtils.isNotEmpty(list)) {
            wwytEduCertificateUserService.updateBatchById(list);
        }
    }
}
